using System;
using System.Collections.Generic;

namespace Elev.UI
{
    internal class SelectedStudentObserver
    {
        static SelectedStudentObserver instance;
        static readonly object padlock = new object();

        int selectedStudentIndex;
        List<IStudentSelector> studentSelectors;

        public int SelectedStudentIndex
        {
            get { return selectedStudentIndex; }
            set
            {
                selectedStudentIndex = value;
                Notify();
            }
        }

        protected SelectedStudentObserver()
        {
            selectedStudentIndex = 0;
            studentSelectors = new List<IStudentSelector>();
        }

        static public SelectedStudentObserver Current
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                        instance = new SelectedStudentObserver();

                    return instance;
                }
            }
        }        

        public void Attach(IStudentSelector StudentSelector)
        {
            studentSelectors.Add(StudentSelector);
        }

        public void Detach(IStudentSelector StudentSelector)
        {
            studentSelectors.Remove(StudentSelector);
        }

        public void Notify()
        {
            foreach (IStudentSelector studentSelector in studentSelectors)
            {
                studentSelector.UpdateSelectedStudent(selectedStudentIndex);
            }
        }
    }
}
